<template>
  <q-page>
    
    <q-inner-loading visible v-if="loading">
      <q-spinner-gears size="50px" color="primary" />
      <b class="text-primary">数据加载中...</b>
    </q-inner-loading>

    <!-- header -->
    <q-toolbar color="primary" >
      <q-toolbar-title class="q-pa-none">
          <!-- <q-select style="width: 120px" inverted hide-underline v-model="currentType" :options="typesList" @input="typeChange" /> -->
      </q-toolbar-title>
      <q-toolbar-title shrink>
        <span slot="subtitle" class="text-right">
          <div><b>{{this.list.length}}</b>个</div>
          <div>当前筛选</div>
        </span>
      </q-toolbar-title>
    </q-toolbar>

    <q-infinite-scroll :handler="loadMoreAccount" :offset="100" ref="infiniteScroll">
      <div class="bg-white">
        <div class="q-pa-xs">
            <q-btn 
                v-for="(catetory,idx) in allCategories" 
                :key="catetory.id + '-' + idx"
                @click.stop="changeCategory(catetory.name)"
                :label="catetory.name"
                :outline="currentCategory !== catetory.name" 
                dense 
                color='primary' 
                class='q-ma-xs'
            />
        </div>


        <q-item style="padding:0;">
          <q-search 
            icon="mdi-account-search" 
            class="full-width no-shadow" 
            inverted-light 
            color="grey-2"
            placeholder="可通过分类、公众号名称、公众号ID、Tag搜索" 
            autofocus="true"
            clearable
            :value="filter"
            @clear="filterResult('')" 
            @change="filterResult" 
            @input="filterResult"
        />
        </q-item>
    </div>
      <!-- list -->
      <q-list separator v-if="currentType === 'account'">

        <q-item v-if="!this.list.length && !loading">暂无数据</q-item>

        <q-item 
            class='column q-pa-none'
            v-for="(item,idx) in this.list" 
            :key="'user_'+item.accountid+idx" 
            :to="'/offical/' + item.accountid"
        >
            <q-item class="full-width"
            >
                <q-item-side class='accoutAvatar' :style="'background-image: url(https://open.weixin.qq.com/qr/code?username=' + item.accountid" />
                <q-item-main>
                    <q-item-tile label>
                        {{item.accountname}} {{item.accountid}}
                        <q-chip color="primary" dense v-if="item.needTagCount">{{item.needTagCount}}篇待操作</q-chip>
                    </q-item-tile>
                    <div class="q-mt-sm">
                        <q-chip class="q-mr-xs" dense>阅读：{{formatNumbers(item.dailyTotal)}}</q-chip>
                        <q-chip class="q-mr-xs" dense>头条：{{formatNumbers(item.headReadAva)}}</q-chip>
                        <q-chip class="q-mr-xs" dense>收藏：{{formatNumbers(item.favorAva)}}</q-chip>
                        <span v-if="!$q.platform.is.mobile">
                          <q-chip class="q-mr-xs" dense>在看率：{{formatNumbers(item.likespercent)}}</q-chip>
                          <q-chip class="q-mr-xs" dense>粉丝：{{formatNumbers(item.fanscount)}}</q-chip>
                        </span>
                    </div>
                </q-item-main>
                <q-item-side right icon="mdi-chevron-right" />
            </q-item>
            
            <q-item class="full-width q-pt-none">
                <q-item-main>
                    <q-chip 
                    v-for="(tag,idx) in item.formatTags" 
                    :key="'ut_' + item.accountid +idx"
                    color="teal"
                    class="q-mr-xs q-mb-xs"
                    dense outline
                    size="xs"
                    >
                        {{tag.key}}
                    </q-chip>
                </q-item-main>
                <q-btn right dense flat outline no-wrap
                    icon="delete_outline"
                    label="删除"
                    color="grey-6"
                    @click.stop.prevent="removeAccounts(item)"
                />
            </q-item>
            <!-- <div class="col row q-col-gutter-sm">
                <div class="col-2" v-for="n in 5" :key="`sm-${n}`">
                    <q-chip dense square color="teal">电影</q-chip>
                </div>
            </div> -->
        </q-item>
      </q-list>
    </q-infinite-scroll>

  </q-page>
</template>

<script>
/**
 * "accountid": "vipidy",
  "accountname": "电影工厂",
  "category": "影视",
  "score": 1094,
  "dailyTotal": 86269,
  "headReadAva": 52737,
  "dailyReadAva": 29327,
  "favorAva": 896,
 */
export default {
  name: 'PageIndexOffical',
  data () {
    return {
      allCategories: [],
      allAccount: [],
      currentType: 'account',
      // typesList: [
      //     { label: '热门账号', value: 'account' },
      //     { label: '热门文章', value: 'artical' },
      // ],
      currentCategory: '全部分类',
      filter: '',     
      modal: false,
      currentUser: {},
      limit: 20,
      page: 1,
      list: [],
      ids: new Set(),
      loading: true,
      timer: null
    }
  },
  mounted() {
    this.$api.ui.pageTitle = '公众号管理';
    this.loadCategories();
    this.loadAllAccounts();
    this.$refs.scroll && this.$refs.scroll.loadMore();
  },
  methods: {
      loadCategories(page, done) {
        let me = this;
        this.$api.offical.loadCategories( data => {
            // this.loading = false
            // console.log( data )
            this.allCategories = [...data]
        });
      },
      loadAllAccounts( ){
          this.$api.offical.loadAccountByCategory( data => {
            this.loading = false
            this.allAccount = [...data]
            this.currentCategory = this.$q.sessionStorage.get.item( 'currentCategory' ) || '全部分类'
            console.log('this.currentCategory:::', this.currentCategory )
            if( this.currentCategory === '全部分类' ){
              this.resetList()
            } else {
              this.changeCategory( this.currentCategory, true )
            }
          })  
      },
      resetList(){
        //   this.$refs && this.$refs.infiniteScroll && this.$refs.infiniteScroll.resume()
          this.list = this.allAccount.slice( 0, this.page * this.limit )
      },
      changeCategory(category, isstartup ){
          // console.log( 'category:::', category )
          this.filter = ''
          this.currentCategory = category
          this.$q.sessionStorage.set( 'currentCategory', category )
          if( category == '全部分类' ){
              this.$refs.infiniteScroll.resume()
              this.resetList()
              return 
          }

          try{
            this.$refs.infiniteScroll.stop()
          } catch (e){
            console.log( e )
          }

          this.list = this.allAccount.filter( item => {
              return item.category === category
          })
      },
      filterResult( val ) {
          console.log( 'filter:::', val )
          this.filter = val
          if( !!this.timer ){
              clearTimeout( this.timer )
          }

          let query = val.toLowerCase();

          if( !query ){
              this.$refs.infiniteScroll.resume()
              this.resetList()
              return
          }

          this.$refs.infiniteScroll.stop()
          
          this.timer = setTimeout( () => {
              this.list = this.allAccount.filter( account =>  {
                if(query.length>0) {
                    if( account.accountname && account.accountname.toLowerCase().indexOf(query)>=0) {
                        return true;
                    }
                    if( account.accountid && account.accountid.toLowerCase().indexOf(query)>=0 ) {
                        return true;
                    }   
                    if( account.category && account.category.toLowerCase().indexOf(query)>=0 ) {
                        return true
                    }
                    if( account.tags && account.tags.join('').indexOf( query ) >= 0 ){
                        return true
                    }
                    return false;
                }
                return true;
            })

          }, 300 )
      },
      loadMoreAccount(page, done) {
        //   if( !!this.filter ){
        //       return
        //   }
          console.log( 'page:::', page )
          setTimeout( () => {
              this.page = page
              this.$refs.infiniteScroll.resume()
              this.resetList()
              done( page >= Math.ceil( this.allAccount.length / this.limit ) )
          })
        //   this.list = this.allAccount.slice( 0, page * this.limit )
        //   done( page >= Math.ceil( this.allAccount.length / this.limit ))
      },
      formatNumbers( num ){
          let number = '' + num
          let showStr = ''
          if( number > 99999 ){
              showStr = '10w+' 
          } else if ( number > 9999 && number < 100000  ){
              showStr = Math.floor(number /  10000) + 'w+'
          } else if ( number > 999 && number < 10000){
              showStr = Math.floor(number / 1000 ) + 'k+'
          } else {
              showStr = number
          }

          return showStr
      },
      formatTags( tags ){
        let resultTags = []
        tags.map( tag => {
          if( !!tag && !resultTags.includes( tag) ){
            resultTags.push( tag )
          }
        })

        return resultTags
      },
      removeAccounts( item ){
          let { accountid, accountname } = item
        //   console.log( this.$q.dialog )
          let _dialog = this.$q.dialog({
                dark: true,
                title: '确认',
                message: '确认删除该账号吗？',
                cancel: '取消',
                ok: '确认删除',
                persistent: true
          }).then( () => {
            this.$api.offical.deleteAccount( accountid ,() => {
                for( let i = 0; i < this.list.length; i ++ ){
                    let _localItem = this.list[i]
                    if( _localItem.accountid == accountid){
                        this.list.splice( i, 1 )
                        this.$q.notify({
                            message: '删除成功',
                            position: 'center',
                            timeout: 1500,
                            color: 'negative'
                        })
                        break
                    }
                }
            })
          }).catch( () => {
              console.log('cancel')
          })
      }
  }
}
</script>

<style>
main div.q-btn-inner>i:last-child {
  display:none;
}

.q-input-chips .q-chip {
  margin: 5px;
}

.accoutAvatar{
    height: 40px;
    width: 40px;
    background-repeat: no-repeat;
    background-position: center;
    background-size: 200px;
    border-radius: 40px;
    box-shadow: 0 0 2px rgba(0, 0, 0, 0.6 );
}
</style>
